package it.evento.controllers;

import it.evento.Comments;
import it.evento.EventPrintable;
import it.evento.Eventsfeedback;
import it.evento.utils.genpage.Article;
import it.evento.utils.genpage.Comment;
import it.evento.utils.genpage.StringHelper;
import it.evento.utils.genpage.Useful;
import java.text.DateFormat;
import java.text.Format;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.JsonObjectBuilder;
import org.apache.commons.lang3.time.DateUtils;
import com.google.gson.Gson;
import it.evento.Users;
import it.evento.BusinessLogic;
import it.evento.Events;
import it.evento.Eventtypes;
import it.evento.Location;
import it.evento.Usertypes;
import it.evento.utils.genpage.ArticleRow;
import it.evento.utils.genpage.BlogPost;
import it.evento.utils.genpage.ContentGenerator;
import it.evento.utils.genpage.RowCell;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonBuilderFactory;
import javax.json.JsonObject;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.digest.DigestUtils;

/**
 *
 * @author Ilo
 */
public class Controller extends HttpServlet {

    @EJB
    private BusinessLogic businessLogic;
    
    private final JsonBuilderFactory factory = Json.createBuilderFactory(null);
    private JsonArray jsonArray = null;
    private JsonObject jsonObj = null;
    private JsonArrayBuilder jsonArrayBld = null;
    
    private HttpSession session;
    private static Users loggedUser;
        
    public Controller() {
        this.session = null;
    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
        response.setContentType("text/html;charset=UTF-8");

        JsonArrayBuilder jaBuild = factory.createArrayBuilder();
        JsonObjectBuilder joBuild = factory.createObjectBuilder();

        
        int idUser = -1;
        int idEvent = -1;
        String htmlContent = "";
        String name = "", surname = "", desc = "";
        String errorMessage = "";
        Date birthdate; 
        List list;
        Events event;
        Gson gson;
        int status;        
        String output;
        boolean flag;
        //Codice Aggiunto
        Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
        List<Location> locList=businessLogic.getAllLocations();
        List<Eventtypes> tevList=businessLogic.getAllEventTypes();
        
        try (PrintWriter out = response.getWriter()) {
            switch (request.getParameter("type")) {
                case "logout":
                    session.removeAttribute("loggedUser");

                    // defines the list of cookies
                    Cookie[] cookiesList = request.getCookies();
                    for (Cookie userCookie : cookiesList) {
                        if (userCookie.getName().equals("EvenTO-user-info")) {
                            userCookie.setMaxAge(0);
                            response.addCookie(userCookie);

                            break;
                        }
                    }

                    // redirects to previous page
                    response.sendRedirect(request.getHeader("referer"));

                    break;
               
                case "insertUser":
                    String u_name = request.getParameter("name");
                    surname = request.getParameter("surname");
                    String  birthY = request.getParameter("birthY");
                    String  birthM = request.getParameter("birthM");
                    String  birthD = request.getParameter("birthD");
                    String company = request.getParameter("company");
                    String info = request.getParameter("info");
                    String username = request.getParameter("username");
                    String pwd = request.getParameter("pwd1");
                    String pwddb = DigestUtils.sha1Hex(username + ":EvenTO:" + pwd);
                    boolean maybePublisher=Boolean.parseBoolean(request.getParameter("publisher"));
                    int bePublisher=0;
                    
                    DateFormat dateFormat = new SimpleDateFormat("yyyy MM dd");
                    Date birthDate=dateFormat.parse(birthY+" "+birthM+" "+birthD);
                    
                    if(maybePublisher)
                        bePublisher=1;
                    boolean insert=businessLogic.insertUsers(u_name, surname, birthDate, company, info, username, pwddb,bePublisher);
                    
                    if(insert){
                        status=0; 
                        output="<li>Utente inserito correttamente</li>";
                    }else{
                        status=1;
                        output="<li>invalid username, please change username</li>";
                    }

                    jsonArray = factory.createArrayBuilder()
                                    .add(factory.createObjectBuilder()
                                        .add("status", status)
                                        .add("message", output))
                                    .build();

                    out.print(ContentGenerator.getOutputJson(jsonArray));
                    
                    break;
                    
                case "manageUsers":                 
                    request.setAttribute("userList", businessLogic.getAllUsers());//-> List<Users>
                    request.getRequestDispatcher("manageUsers.jsp").forward(request, response);
                    break;
                    
                case "cancelUsers":
                    String  delArrayU = request.getParameter("idUsers");                  
                    String[] tokensU = delArrayU.split(",");
                    flag=true;
                   
                    for (String id : tokensU){
                        if(!businessLogic.removeUser(Integer.parseInt(id)))
                            flag=false;
                    }

                    if(flag){
                        status=0; 
                        output="<li>User cancellato correttamente</li>";
                    }else{
                        status=1;
                        output="<li>Riprova a cancellare l'utente</li>";
                    }

                    jsonArray = factory.createArrayBuilder()
                                    .add(factory.createObjectBuilder()
                                        .add("status", status)
                                        .add("message", output))
                                    .build();

                    out.print(ContentGenerator.getOutputJson(jsonArray));
                    break;    
                    
                //inoltra a manageEvents.jsp la lista di eventi da modificare qunado clicco su modifica
                case "forwardUsers":
                    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
                    if (!request.getParameter("idUsers").isEmpty()) {
                        String[] tokens2 = (request.getParameter("idUsers")).split(",");
                        List<Users> userForward= new LinkedList<Users>();
                        List<Usertypes> lut=businessLogic.getAllUsertypes();

                        
                       for (String id : tokens2) {//scelgo gli utenti richiesti
                           userForward.add(businessLogic.getUser(Integer.parseInt(id)));                          
                       }
                        
                        htmlContent = ""; 
                        for(Users u:userForward){
                            String compleanno="";
                            String optionType="",optionUpgrade="";
                            try{
                                compleanno=DATE_FORMAT.format(u.getBirth());
                            }catch(java.lang.NullPointerException e){}//no data compleanno                                                 

                            for(Usertypes ut:lut){
                                if(ut.getId().equals(u.getType()))
                                    optionType+="<option value="+ut.getId()+" selected>"+ut.getName()+"</option>";
                                else
                                    optionType+="<option value="+ut.getId()+">"+ut.getName()+"</option>";
                            }
                            
                            if(u.getUpgrade().equals(1)){
                                optionUpgrade="<option value=1 selected> 1 </option>"
                                        + "<option value=0> 0 </option>";
                            }else{
                                optionUpgrade="<option value=0 selected> 0 </option>"
                                        + "<option value=1> 1 </option>";
                            }
                            
                            htmlContent += new Article()
                                    .setTitle(u.getUsername())
                                    .setContent(
                                            "Username: <input type='text' id='" + u.getId() + "_username' value='" + u.getUsername() + "'/>"
                                            + "Nome: <input type='text' id='" + u.getId() + "_name' value='" + u.getName() + "'/>"
                                            + "Cognome: <input type='text' id='" + u.getId() + "_surname' value='" + u.getSurname() + "'/>"
                                            + "Compleanno: <input type='text' id='" + u.getId() + "_birth' value='" + compleanno + "'/>"
                                            + "Organizzazione: <input type='text' id='" + u.getId() + "_company' value='" + u.getCompanyname() + "'/>"
                                            + "Tipo:<br><select id='" + u.getId() + "_type' >" +optionType+ "</select><br>"                                            
                                            + "Upgrade:<br> <select id='" + u.getId() + "_upgrade' >" +optionUpgrade+ "</select><br><br>"
                                            + "<input type='button' value='Conferma' id='" + u.getId() + "_add' class='evento-button' />"//submit
                                            + "<input type='button' value='Annulla' id='" + u.getId() + "_cancel' class='evento-button' />").print();

                        }

                        jsonArray = factory.createArrayBuilder()
                                .add(factory.createObjectBuilder()
                                        .add("status", 0)
                                        .add("message", htmlContent))
                                .build();

                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    } else {
                        jsonArray = factory.createArrayBuilder()
                                .add(factory.createObjectBuilder()
                                        .add("status", 1)
                                        .add("message", "Array vuoto"))
                                .build();

                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    }
                    break;
                    
                /*
                    manageUsers.jsp -- Modifiche + utenti --> Controller-modifyUsers 
                    Controller-modifyUsers, esegue le modifiche sul DB
                    Controller-modifyUsers -- utenti da modificare --> manageUsers.jsp
                */
                
                case "modifyUsers":
                    /*[INPUT]*/
                    String idUs = request.getParameter("idModUsers");
                    String usernameUs=request.getParameter("usernameModUser");
                    String nameUs=request.getParameter("nameModUser");
                    String surnameUs=request.getParameter("surnameModUser");
                    String birthUs=request.getParameter("birthModUser");
                    String companyUs=request.getParameter("companyModUser");                    
                    int typeUs=3;
                    int upgradeUs=0;
                    
                    /*[CONTROLLI]*/
                    flag=false;//controlli superati -> flag=true     
                    DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
                    try{
                        if(!idUs.equals("") && !usernameUs.equals("")){
                            typeUs=Integer.parseInt(request.getParameter("typeModUser"));
                            upgradeUs=Integer.parseInt(request.getParameter("upgradeModUser"));
                            DATE_FORMAT.parse(birthUs);//controlla se è una data
                            flag=true;
                        }
                    }catch(Exception e){System.out.println("Controller: "+e);}           
                       
                    if(flag){
                       businessLogic.modifyUser(idUs, usernameUs, nameUs, surnameUs, birthUs, companyUs, typeUs, upgradeUs);
                    }else{
                        jsonArray = factory.createArrayBuilder()
                                   .add(factory.createObjectBuilder()
                                       .add("status", 1)
                                       .add("message", "<li>Errore di nei dati, riempire i campi correttamente</li>"))
                                   .build();
                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    }
                    
                    //REINVIO EVENTI NON MODIFICATI 
                    if(request.getParameter("idUsers").isEmpty()&& flag){
                         jsonArray = factory.createArrayBuilder()
                                .add(factory.createObjectBuilder()
                                        .add("status", 0)
                                        .add("message", ""))
                                .build();
                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    }
                    if (!request.getParameter("idUsers").isEmpty() && flag) {
                        //CODICE DELLA FORWARD USERS
                        String[] tokens2 = (request.getParameter("idUsers")).split(",");
                        List<Users> userForward= new LinkedList<Users>();
                        List<Usertypes> lut=businessLogic.getAllUsertypes();                        
                        
                       for (String id : tokens2) {//scelgo gli utenti richiesti
                           userForward.add(businessLogic.getUser(Integer.parseInt(id)));                          
                       }
                        
                        htmlContent = ""; 
                        for(Users u:userForward){
                            String compleanno="";
                            String optionType="",optionUpgrade="";
                            try{
                                compleanno=DATE_FORMAT.format(u.getBirth());
                            }catch(java.lang.NullPointerException e){}//no data compleanno                                                 

                            for(Usertypes ut:lut){
                                if(ut.getId().equals(u.getType()))
                                    optionType+="<option value="+ut.getId()+" selected>"+ut.getName()+"</option>";
                                else
                                    optionType+="<option value="+ut.getId()+">"+ut.getName()+"</option>";
                            }
                            
                            if(u.getUpgrade().equals(1)){
                                optionUpgrade="<option value=1 selected> 1 </option>"
                                        + "<option value=0> 0 </option>";
                            }else{
                                optionUpgrade="<option value=0 selected> 0 </option>"
                                        + "<option value=1> 1 </option>";
                            }
                            
                            htmlContent += new Article()
                                    .setTitle(u.getUsername())
                                    .setContent(
                                            "Username: <input type='text' id='" + u.getId() + "_username' value='" + u.getUsername() + "'/>"
                                            + "Nome: <input type='text' id='" + u.getId() + "_name' value='" + u.getName() + "'/>"
                                            + "Cognome: <input type='text' id='" + u.getId() + "_surname' value='" + u.getSurname() + "'/>"
                                            + "Compleanno: <input type='text' id='" + u.getId() + "_birth' value='" + compleanno + "'/>"
                                            + "Organizzazione: <input type='text' id='" + u.getId() + "_company' value='" + u.getCompanyname() + "'/>"
                                            + "Tipo:<br><select id='" + u.getId() + "_type' >" +optionType+ "</select><br>"                                            
                                            + "Upgrade:<br> <select id='" + u.getId() + "_upgrade' >" +optionUpgrade+ "</select><br><br>"
                                            + "<input type='button' value='Conferma' id='" + u.getId() + "_add' class='evento-button' />"//submit
                                            + "<input type='button' value='Annulla' id='" + u.getId() + "_cancel' class='evento-button' />").print();
                        }

                        jsonArray = factory.createArrayBuilder()
                                .add(factory.createObjectBuilder()
                                        .add("status", 0)
                                        .add("message", htmlContent))
                                .build();

                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    }
                    
                    break;

                case "insertEvent":   
                     /* INPUT*/
                    name = request.getParameter("eventName");
                    desc = request.getParameter("eventDescription");
                    String start = request.getParameter("eventStartDate");
                    String end = request.getParameter("eventEndDate");
                    String location = request.getParameter("eventLocation");
                    String link = request.getParameter("eventLink");
                    int type = Integer.parseInt(request.getParameter("eventType"));
                    Users publisher=(Users)session.getAttribute("loggedUser");
                     /* /INPUT*/
     
                    /* CONTROLLI*/
                    flag=true;
                    String error="";
                    Date startD=new Date();
                    Date endD=new Date();
                    
                    if(name.equals("")){
                        flag=false;
                        error+="<li>empty name</li>";
                    }
                    if(desc.equals("")){
                        flag=false;
                        error+="<li>empty description</li>";
                    }
                    if(start.equals("") || end.equals("")){
                        flag=false;
                        error+="<li>incorrect Date</li>";
                    }else{//controlli e pasificazione date                         
                        startD = new SimpleDateFormat("MM/dd/yyyy HH:mm").parse(start);
                        endD = new SimpleDateFormat("MM/dd/yyyy HH:mm").parse(end);  

                        /* sottraggo qualche minuto alla data corrente*/
                        Date currentDate= DateUtils.addMinutes(new Date(),-5);
                        
                        if(startD.before(currentDate) || endD.before(startD) ){
                            flag=false;
                            error+="<li>incorrect date</li>";
                        }
                    }
                    
                    int locId=businessLogic.locationId(location);
                    if (locId< 0) { // -> location non definita 
                        flag=false;
                        error+="<li>No define location, please define new location</li>";
                    }
                    
                    /* /CONTROLLI*/
      
                    if(flag){
                        businessLogic.insertEvent(name, desc, startD, endD, locId, publisher.getUsername(), type, link);      
                        jsonArray = factory.createArrayBuilder()
                            .add(factory.createObjectBuilder()
                                    .add("status", 0)
                                    .add("message", "<li>evento inserito correttamente</li>"))
                            .build();

                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    }else{
                        jsonArray = factory.createArrayBuilder()
                                .add(factory.createObjectBuilder()
                                        .add("status", 1)
                                        .add("message", error))
                                .build();
                        
                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    }              
                    break;
                    
                case "insertLocation":                    
                    String nameLoc=request.getParameter("eventLocationName");
                    String addressLoc=request.getParameter("eventLocationAddress");
                    String descriptionLoc=request.getParameter("eventLocationDescription");  
                    int esito=businessLogic.insertLocation(nameLoc,addressLoc,descriptionLoc);
                    if(esito!=-1){
                         jsonArray = factory.createArrayBuilder()
                              .add(factory.createObjectBuilder()
                                      .add("status", 0)
                                      .add("message", "<li>Location insert success</li>"))
                              .build();
                    }else{
                         jsonArray = factory.createArrayBuilder()
                              .add(factory.createObjectBuilder()
                                      .add("status", 1)
                                      .add("message", "<li>Location insert fail</li>"))
                              .build();
                    }
                    out.print(ContentGenerator.getOutputJson(jsonArray));
                    
                    break;
                    
                case "getlocations":
                    List<Location> locOld = businessLogic.getAllLocations();

                    for (Location l : locOld) {
                        joBuild.add("label", l.getName());
                        joBuild.add("id", l.getId());
                        joBuild.add("description", l.getDescription());
                        joBuild.add("geolocation", l.getGeolocation());
                        joBuild.add("address", l.getAddress());
                        
                        jaBuild.add(joBuild);
                    }

                    out.print(jaBuild.build().toString());
                    System.out.println(jaBuild.build().toString());
                    break;
               
                case "getType":
                    List<Eventtypes> te = businessLogic.getAllEventTypes();
                    for (Eventtypes e : te) {
                        joBuild.add("label", e.getName());
                        joBuild.add("id", e.getId());

                        jaBuild.add(joBuild);
                    }
                    out.print(jaBuild.build().toString());
                    
                    break;
                    
               case "getAllEvents":
                    List<Events> events_list =businessLogic.getAllEvents();
                    for(Events e:events_list){
                        joBuild.add("id",e.getId());
                        joBuild.add("label",e.getName());
                        
                        jaBuild.add(joBuild);
                    }
                    
                    out.print(jaBuild.build().toString());

                    break;       
                                  
                case "getTypedEvents":               
                    request.setAttribute("eventsList", businessLogic.getOnlyTypeEvents(Integer.parseInt(request.getParameter("eventsType"))));
                    request.getRequestDispatcher("showEvent.jsp").forward(request, response);   
                    
                    break;
                    
                case "searchEvent":
                    String nomeEv=request.getParameter("searchBox");
                    List<Events> le=businessLogic.getEvent(nomeEv);
                    if(le.isEmpty()){//evento non trovato
                        htmlContent = new BlogPost()
                                        .setTitle("Spiacenti :(")//piglia il primo ed unico elemento della lista
                                        .setContent("L'evento che cerchi non è stato trovato.")
                                        .print();
                        
                        request.setAttribute("content", htmlContent);
                        request.getRequestDispatcher("showEvent.jsp").forward(request, response);
                    }
                    if(le.size()==1){//un evento trovato                        
                        htmlContent = new BlogPost()
                                        .setTitle(le.get(0).getName())//piglia il primo ed unico elemento della lista
                                        .setContent(le.get(0).getDescription())
                                        .setAuthor(le.get(0).getPublisher())
                                        .print();
                        
                        request.setAttribute("eventName", le.get(0).getName());
                        request.setAttribute("content", htmlContent);
                        request.getRequestDispatcher("showEvent.jsp").forward(request, response);
                    }                    
                    if(le.size()>1){//più eventi trovati
                        htmlContent="";
                        for(Events e:le){
                            List<Eventsfeedback> lstStars = businessLogic.getEventsFeedback(e.getId());
                        
                             htmlContent += new BlogPost()
                                        .setTitle(e.getName())//piglia il primo ed unico elemento della lista
                                        .setContent(e.getDescription())
                                        .setAuthor(e.getPublisher())
                                        .setStars(Useful.calculateStars(lstStars))
                                        .setRatesNumber(lstStars.size())
                                        .setID(""+e.getId())
                                        .print();
                        }
                        request.setAttribute("content", htmlContent);
                        request.getRequestDispatcher("showEvent.jsp").forward(request, response);
                    }
                        
                    break;
                    
                case "advancedSearchEvent":
                    /*CONTROLLI*/
                    
                    type=Integer.parseInt(request.getParameter("eventType"));
                    int idLoc=Integer.parseInt(request.getParameter("eventLoc"));
                    start = request.getParameter("eventStartDate");//parsificazione fatta in BusinessLogic
                    end=request.getParameter("eventEndDate"); //parsificazione fatta in BusinessLogic          
                    String match=request.getParameter("matchBox");
                    le=businessLogic.advancedSearchEvent(type, idLoc, start, end, match);
                    
                    request.setAttribute("eventsList",le);
                    request.getRequestDispatcher("showEvent.jsp").forward(request, response); 
                    
                    break;
                    
                case "insertComment":
                    idEvent = Integer.parseInt(request.getParameter("idEvent"));
                    Users currentUser = (Users) session.getAttribute("loggedUser");
                    String comment = request.getParameter("comment");

                    businessLogic.insertComment(idEvent, currentUser.getId(), comment, new Date());

                    // redirects to previous page
                    response.sendRedirect(request.getHeader("referer"));
                    
                    break;
                case "manageEvents":
                    Users you=(Users)session.getAttribute("loggedUser");
                    List<Events> eventsList=new LinkedList<Events>();
                    List<EventPrintable> evPrintList= new LinkedList<EventPrintable>(); //evento in formato stampabile per jsp                    
                   
                    if(you.getType()==1){//Admin
                        eventsList =businessLogic.getAllEvents();
                    }
                    
                    if(you.getType()==2){//Publisher
                        eventsList=businessLogic.getUserEvents(you.getUsername());
                    }
                    
                    //Usa il formatter dichiarato sopra al case               
                    for(Events e:eventsList){                     
                        String sDate = formatter.format(e.getStartdate());
                        String eDate= formatter.format(e.getEnddate());

                        EventPrintable c= new EventPrintable(e.getId(),e.getName(),e.getDescription(),sDate,eDate,e.getPublisher());
                        for(Location l:locList){
                            if(e.getLocation()==l.getId())
                                c.setLocation(l.getName());
                        }
                        for(Eventtypes t:tevList){
                            if(e.getType()==t.getId())
                                c.setType(t.getName());
                        }
                        
                        evPrintList.add(c);
                    }
                    
                    request.setAttribute("eventsList", evPrintList);
                    request.getRequestDispatcher("manageEvents.jsp").forward(request, response);
                    
                    break;
                    
                case "cancelEvents":
                    String  delArray = request.getParameter("idEvents");               
                    String[] tokens = delArray.split(",");
                    flag=true;
                   
                    for (String id : tokens){
                        if(!businessLogic.removeEvent(Integer.parseInt(id)))
                            flag=false;
                    }

                    if(flag){
                        status=0; 
                        output="<li>Evento cancellato correttamente</li>";
                    }else{
                        status=1;
                        output="<li>Riprova a cancellare l'evento</li>";
                    }

                    jsonArray = factory.createArrayBuilder()
                                    .add(factory.createObjectBuilder()
                                        .add("status", status)
                                        .add("message", output))
                                    .build();

                    out.print(ContentGenerator.getOutputJson(jsonArray));

                    break;
                    
                //inoltra a manageEvents.jsp la lista di eventi da modificare qunado clicco su modifica
                case "forwardEvents":                  
                    if (!request.getParameter("idEvents").isEmpty()) {
                        String[] tokens2 = (request.getParameter("idEvents")).split(",");
                        List<Events> evForward = new LinkedList();
                        List<EventPrintable> evPrintList2 = new LinkedList<EventPrintable>();
                        Events current;

                        for (String id : tokens2) {
                            current = businessLogic.getEvent(Integer.parseInt(id));
                            evForward.add(current);
                        }

                        for (Events e : evForward) {
                            String sDate = formatter.format(e.getStartdate());
                            String eDate = formatter.format(e.getEnddate());

                            EventPrintable c = new EventPrintable(e.getId(), e.getName(), e.getDescription(), sDate, eDate, e.getPublisher());
                            for (Location l : locList) {
                                if (e.getLocation() == l.getId()) {
                                    c.setLocation(l.getName());
                                }
                            }
                            for (Eventtypes t : tevList) {
                                if (e.getType() == t.getId()) {
                                    c.setType(t.getName());
                                }
                            }

                            evPrintList2.add(c);
                        }
                        //carica la lista dei possibili tipi di eventi e dopo delle location
                        List<Eventtypes> lt=businessLogic.getAllEventTypes();
                        List<Location> ll=businessLogic.getAllLocations();
                        
                        htmlContent = "";
                        for (EventPrintable e : evPrintList2) {
                            String option="";
                            for(Eventtypes t:lt){                                
                                if(e.getType().equals(t.getName()))
                                    option+="<option value="+t.getId()+" selected>"+t.getName()+"</option>";
                                else
                                    option+="<option value="+t.getId()+">"+t.getName()+"</option>";
                            }

                            String option1="";
                            for(Location l:ll){
                                if(e.getLocation().equals(l.getName()))
                                 option1+="<option value="+l.getId()+" selected>"+l.getName()+"</option>";
                                else
                                    option1+="<option value="+l.getId()+">"+l.getName()+"</option>";
                            }
                        
                            htmlContent += new Article()
                                    .setTitle(e.getName())
                                    .setContent(
                                            "Nome: <input type='text' id='" + e.getId() + "_name' value='" + e.getName() + "'/>"
                                            + "Descrizione: <input type='text' id='" + e.getId() + "_desc' value='" + e.getDescription() + "'/>"
                                            //+ "Location: <input type='text' id='" + e.getId() + "_loc' value='" + e.getLocation() + "'/>"
                                            + "Location:<br><select id='" + e.getId() + "_loc' >" +option1+ "</select><br>"
                                            //+ "Tipo: <input type='text' id='" + e.getId() + "_type' value='" + e.getType() + "'/>"
                                            + "Tipo:<br> <select id='" + e.getId() + "_type' >" +option+ "</select><br>"
                                            + "Data Inizio: <input type='text' id='" + e.getId() + "_start' value='" + e.getStartDate() + "'/>"
                                            + "Data Fine: <input type='text' id='" + e.getId() + "_end' value='" + e.getEndDate() + "'/>"
                                            + "<input type='button' value='Conferma' id='" + e.getId() + "_add' class='evento-button' />"//submit
                                            + "<input type='button' value='Annulla' id='" + e.getId() + "_cancel' class='evento-button' />").print();
                                                                  
                        }

                        jsonArray = factory.createArrayBuilder()
                                .add(factory.createObjectBuilder()
                                        .add("status", 0)
                                        .add("message", htmlContent))
                                .build();

                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    } else {
                        jsonArray = factory.createArrayBuilder()
                                .add(factory.createObjectBuilder()
                                        .add("status", 1)
                                        .add("message", "Array vuoto"))
                                .build();

                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    }
                    
                    break;
                    
                //Riceve dati modificati da manageEvents.jsp e ritorna la lista degli eventi ancora da modificare
                case "modifyEvents":
                    /* INPUT*/
                    String idEv = request.getParameter("idModEvent");
                    String nameEv = request.getParameter("nameModEvent");
                    String descEv = request.getParameter("descModEvent");
                    String startEv = request.getParameter("startModEvent");
                    String endEv = request.getParameter("endModEvent");
                    int locEv = 0,
                     typeEv = 0;

                    /* CONTROLLI*/
                    boolean errors = false;
                    if (nameEv.equals("")) 
                        errors = true;
                    
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    try {//se non ci sono errori i dati in input sono corretti
                        locEv = Integer.parseInt(request.getParameter("locModEvent"));
                        typeEv = Integer.parseInt(request.getParameter("typeModEvent"));
                        Date st = df.parse(startEv);
                        Date ed = df.parse(endEv);
                    } catch (Exception e) {
                        errors = true;                  
                    }
                    //Date startEv = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(request.getParameter("startModEvent"));//come formattare la data

                    // MODIFICA EVENTO SCELTO            
                    if (!errors) {
                        businessLogic.modifyEvent(idEv, nameEv, descEv, locEv, typeEv, startEv, endEv);
                    }else{
                        jsonArray = factory.createArrayBuilder()
                                   .add(factory.createObjectBuilder()
                                       .add("status", 1)
                                       .add("message", "<li>Errore di nei dati, riempire i campi correttamente</li>"))
                                   .build();
                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    }
                                        
                    //REINVIO EVENTI NON MODIFICATI    
                    if(request.getParameter("idEvents").isEmpty()&& !errors){
                         jsonArray = factory.createArrayBuilder()
                                .add(factory.createObjectBuilder()
                                        .add("status", 0)
                                        .add("message", ""))
                                .build();
                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    }
                    if (!request.getParameter("idEvents").isEmpty() && !errors) {
                        String[] tokens3 = (request.getParameter("idEvents")).split(",");
                        List<Events> evForward1 = new LinkedList();
                        List<EventPrintable> evPrintList3 = new LinkedList<EventPrintable>();
                        Events current1;

                        for (String id : tokens3) {
                            current1 = businessLogic.getEvent(Integer.parseInt(id));
                            evForward1.add(current1);
                        }

                        for (Events e : evForward1) {
                            String sDate = formatter.format(e.getStartdate());
                            String eDate = formatter.format(e.getEnddate());

                            EventPrintable c = new EventPrintable(e.getId(), e.getName(), e.getDescription(), sDate, eDate, e.getPublisher());
                            for (Location l : locList) {
                                if (e.getLocation() == l.getId()) {
                                    c.setLocation(l.getName());
                                }
                            }
                            for (Eventtypes t : tevList) {
                                if (e.getType() == t.getId()) {
                                    c.setType(t.getName());
                                }
                            }

                            evPrintList3.add(c);
                        }
                        //carica la lista dei possibili tipi di eventi e dopo delle location
                        List<Eventtypes> lt = businessLogic.getAllEventTypes();
                        List<Location> ll = businessLogic.getAllLocations();

                        String htmlContent2 = "";
                        for (EventPrintable e : evPrintList3) {
                            String option = "";
                            for (Eventtypes t : lt) {
                                if (e.getType().equals(t.getName())) {
                                    option += "<option value=" + t.getId() + " selected>" + t.getName() + "</option>";
                                } else {
                                    option += "<option value=" + t.getId() + ">" + t.getName() + "</option>";
                                }
                            }

                            String option1 = "";
                            for (Location l : ll) {
                                if (e.getLocation().equals(l.getName())) {
                                    option1 += "<option value=" + l.getId() + " selected>" + l.getName() + "</option>";
                                } else {
                                    option1 += "<option value=" + l.getId() + ">" + l.getName() + "</option>";
                                }
                            }

                            htmlContent2 += new Article()
                                    .setTitle(e.getName())
                                    .setContent("Nome: <input type='text' id='" + e.getId() + "_name' value='" + e.getName() + "'/>"
                                            + "Descrizione: <input type='text' id='" + e.getId() + "_desc' value='" + e.getDescription() + "'/>"
                                            //+ "Location: <input type='text' id='" + e.getId() + "_loc' value='" + e.getLocation() + "'/>"
                                            + "Location:<br><select id='" + e.getId() + "_loc' >" + option1 + "</select><br>"
                                            //+ "Tipo: <input type='text' id='" + e.getId() + "_type' value='" + e.getType() + "'/>"
                                            + "Tipo:<br> <select id='" + e.getId() + "_type' >" + option + "</select><br>"
                                            + "Data Inizio: <input type='text' id='" + e.getId() + "_start' value='" + e.getStartDate() + "'/>"
                                            + "Data Fine: <input type='text' id='" + e.getId() + "_end' value='" + e.getEndDate() + "'/>"
                                            + "<input type='button' value='Conferma' id='" + e.getId() + "_add' class='evento-button' />"//submit
                                            + "<input type='button' value='Annulla' id='" + e.getId() + "_cancel' class='evento-button' />").print();
                        }
                        jsonArray = factory.createArrayBuilder()
                                .add(factory.createObjectBuilder()
                                        .add("status", 0)
                                        .add("message", htmlContent2))
                                .build();
                        out.print(ContentGenerator.getOutputJson(jsonArray));
                    }

                    break;

                case "loadLastEvents":
                    list = businessLogic.getLastEvents();
                    if(list != null && list.size()>0) {
                        htmlContent = "";
                        LinkedList<Events> eventList = new LinkedList<>();
                        eventList.addAll(list);
                        
                        LinkedList<RowCell> cellsList = new LinkedList<>();
                        
                        for(int k=0; k<eventList.size(); k++) {
                            Events e = eventList.get(k);
                            List<Eventsfeedback> lstStars = businessLogic.getEventsFeedback(e.getId());
                            
                            RowCell cell = new RowCell()
                                            .setTitle(e.getName())
                                            .setContent(Useful.cutText(e.getDescription()))
                                            .setStars(Useful.calculateStars(lstStars))
                                            .setRatesNumber(lstStars.size())
                                            .setID(""+e.getId())
                                            .setLink("Controller?type=showEvent&ide=" + e.getId());
                            
                            if(k!=0 && k%3==0) {
                                htmlContent += new ArticleRow().setCells(cellsList).print();
                                cellsList.clear();
                            }
                            
                            cellsList.add(cell);
                        }
                        
                        htmlContent += new ArticleRow().setCells(cellsList).print();
                        
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 0)
                                            .add("message", htmlContent))
                                        .build();
                    }
                    else {
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 1)
                                            .add("message", ContentGenerator.printError("Non ci sono eventi.")))
                                        .build();
                    }

                    out.print(ContentGenerator.getOutputJson(jsonArray));
                    
                    break;
                    
                 case "searchEventPalnnig":
                     System.out.println("[ searchEventPalnnig]");
                     String dataS=request.getParameter("evStartDate");
                     System.out.println("dataS: "+dataS);
                     type=Integer.parseInt(request.getParameter("eventType"));
                     List<Events> listEventsTyped=businessLogic.getOnlyTypeEvents(type);
                     
                     if(!dataS.equals("")){
                        System.out.println("Data indicata");
                        Date d1 = new SimpleDateFormat("MM/dd/yyyy").parse(dataS);                         
                        
                        for(Events e:listEventsTyped){
                            if(e.getStartdate().after(d1) || e.getStartdate().equals(d1)){
                                joBuild.add("id",e.getId());
                                joBuild.add("label",e.getName());

                                jaBuild.add(joBuild);
                            }                            
                        }
                     }else{
                        System.out.println("Data NON indicata");
                        for(Events e:listEventsTyped){
                                joBuild.add("id",e.getId());
                                joBuild.add("label",e.getName());

                                jaBuild.add(joBuild);
                            }                  

                     }
                     jsonArray = factory.createArrayBuilder()
                            .add(factory.createObjectBuilder()
                                    .add("status", 0)
                                    .add("message", jaBuild.build().toString()))
                            .build();

                     out.print(ContentGenerator.getOutputJson(jsonArray));
                        
                     System.out.println("[ /searchEventPalnnig]");                                            
                     
                     break;
                    
                case "loadFavouriteEvents":
                    idUser = Integer.parseInt(request.getParameter("userid"));

                    list = businessLogic.getFavouriteEvents(idUser);
                    if(list != null && list.size()>0) {
                        htmlContent = "";
                        LinkedList<Events> eventList = new LinkedList<>();
                        eventList.addAll(list);
                        
                        LinkedList<RowCell> cellsList = new LinkedList<>();
                        
                        for(int k=0; k<eventList.size(); k++) {
                            Events e = eventList.get(k);
                            List<Eventsfeedback> lstStars = businessLogic.getEventsFeedback(e.getId());
                            
                            RowCell cell = new RowCell()
                                            .setTitle(e.getName())
                                            .setContent(Useful.cutText(e.getDescription()))
                                            .setStars(Useful.calculateStars(lstStars))
                                            .setRatesNumber(lstStars.size())
                                            .setID(""+e.getId())
                                            .setLink("Controller?type=showEvent&ide=" + e.getId());
                            
                            if(k!=0 && k%3==0) {
                                htmlContent += new ArticleRow().setCells(cellsList).print();
                                cellsList.clear();
                            }
                            
                            cellsList.add(cell);
                        }
                        
                        htmlContent = new ArticleRow().setCells(cellsList).print();
                        
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 0)
                                            .add("message", htmlContent))
                                        .build();
                    }
                    else {
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 1)
                                            .add("message", ContentGenerator.printError("Non ci sono eventi.")))
                                        .build();
                    }

                    out.print(ContentGenerator.getOutputJson(jsonArray));
                    
                    break;
                case "loadProfileInfo":
                    loggedUser = (Users)session.getAttribute("loggedUser");
                    String dateBirth = "";
                    
                    if(loggedUser!=null) {
                        Usertypes ut = businessLogic.getUserTypeById(loggedUser.getType());
                        List<Eventtypes> listEt = businessLogic.getAllEventTypes();
                        HashMap<Integer, String> hashEt = new HashMap<>();
                        for (Eventtypes et : listEt) {
                            hashEt.put(et.getId(), et.getName());
                        }
                        
                        dateBirth = new SimpleDateFormat("dd/MM/yyyy").format(loggedUser.getBirth());
                        
                        jsonObj = factory.createObjectBuilder()
                                    .add("photo", (loggedUser.getPhoto()!=null ? ("images/data/userphotos/" + loggedUser.getPhoto()) : ""))
                                    .add("username", loggedUser.getUsername())
                                    .add("type", loggedUser.getType())
                                    .add("typename", ut.getName())
                                    .add("upgrade", loggedUser.getUpgrade())
                                    .add("name", loggedUser.getName())
                                    .add("surname", loggedUser.getSurname())
                                    .add("birth", dateBirth)
                                    .add("info", loggedUser.getInfo()!=null ? loggedUser.getInfo() : "")
                                    .build();
                        
                        JsonObject jsonObj2 = factory.createObjectBuilder()
                                    .add("company", (loggedUser.getCompanyname()!=null ? loggedUser.getCompanyname() : ""))
                                    .add("tags", (loggedUser.getTag()!=null ? loggedUser.getTag() : ""))
                                    .build();
                        
                        gson = new Gson();
                        
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 0)
                                            .add("profileInfos", jsonObj)
                                            .add("eventsInfos", jsonObj2)
                                            .add("eventTypes", gson.toJson(hashEt)))
                                        .build();
                    }
                    else {
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 1)
                                            .add("message", ContentGenerator.printError("Non hai i permessi di accesso a questa pagina")))
                                        .build();
                    }

                    out.print(ContentGenerator.getOutputJson(jsonArray));
                    
                    break;
                case "saveProfileInfoChanges":
                    errorMessage = "";
                    
                    boolean upgrade = Boolean.parseBoolean(request.getParameter("upgrade"));
                    name = request.getParameter("name");
                    surname = request.getParameter("surname");
                    try {
                        birthdate = new SimpleDateFormat("dd/MM/yyyy").parse(request.getParameter("birth"));
                    } catch (ParseException ex) {
                        birthdate = null;
                    }
                    desc = request.getParameter("info");
                    
                    if(name.trim().equals("")) {
                        if(!errorMessage.equals(""))
                            errorMessage += "<br>";
                        errorMessage += "Errore: Il nome &egrave; obbligatorio.";
                    }
                    if(surname.trim().equals("")) {
                        if(!errorMessage.equals(""))
                            errorMessage += "<br>";
                        errorMessage += "Errore: Il cognome &egrave; obbligatorio.";
                    }
                    if(birthdate == null) {
                        if(!errorMessage.equals(""))
                            errorMessage += "<br>";
                        errorMessage += "Errore: Seleziona una data corretta.";
                    }
                    
                    if(errorMessage.equals("")) {
                        loggedUser.setName(name);
                        loggedUser.setSurname(surname);
                        loggedUser.setInfo(desc);
                        loggedUser.setUpgrade(upgrade ? 1 : 0);
                        loggedUser.setBirth(birthdate);
                        businessLogic.updateUser(loggedUser.getId(), loggedUser);


                        response.sendRedirect("profile.jsp?ok=ok");
                    }
                    else {
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 1)
                                            .add("message", errorMessage))
                                        .build();
                    }

                    out.print(ContentGenerator.getOutputJson(jsonArray));
                    
                    break;
                case "saveEventsChanges":
                    company = request.getParameter("company");
                    String tags = request.getParameter("tags");
                                        
                    gson = new Gson();
                    
                    Integer[] ints = gson.fromJson(tags, Integer[].class);
                    tags = "";
                    for(int i : ints) {
                        tags += i+",";
                    }
                    tags = tags.substring(0, tags.length()-1);
                    
                    loggedUser.setCompanyname(company);
                    loggedUser.setTag(tags);
                    
                    businessLogic.updateUser(loggedUser.getId(), loggedUser);
                    
                    response.sendRedirect("profile.jsp?ok=ok");
                    
                    break;
                case "savePasswordChanges":
                    loggedUser = (Users)session.getAttribute("loggedUser");
                    
                    String pwdOld = request.getParameter("pwdOld");
                    String pwd1 = request.getParameter("pwdNew1");
                    String pwd2 = request.getParameter("pwdNew2");
                    pwddb = DigestUtils.sha1Hex(loggedUser.getUsername() + ":EvenTO:" + pwdOld);
                    errorMessage = "";
                    
                    if(!loggedUser.getPassword().equals(pwddb)) {
                        errorMessage += "Errore: La vecchia password non &egrave; corretta.";
                    }
                    
                    if(!pwd1.equals(pwd2)) {
                        if(!errorMessage.equals(""))
                            errorMessage += "<br>";
                        errorMessage += "Errore: Le due password devono essere uguali!";
                    }
                    
                    if(errorMessage.equals("")) {
                        pwddb = DigestUtils.sha1Hex(loggedUser.getUsername() + ":EvenTO:" + pwd1);
                        
                        businessLogic.updatePassword(loggedUser.getId(), pwddb);
                        
                        response.sendRedirect("profile.jsp?ok=ok");
                    }
                    else {
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 1)
                                            .add("message", errorMessage))
                                        .build();
                    }

                    out.print(ContentGenerator.getOutputJson(jsonArray));
                    
                    break;
                case "eventStarsRate":
                    idEvent = Integer.parseInt(request.getParameter("eventid"));
                    int score = Integer.parseInt(request.getParameter("score"));
                    loggedUser = (Users)session.getAttribute("loggedUser");
                            
                    if(businessLogic.hasEventFeedback(idEvent, loggedUser.getId())) {
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 1)
                                            .add("message", ContentGenerator.printError("Hai gi&agrave; votato questo evento.")))
                                        .build();
                    }
                    else {
                        businessLogic.insertFeedback(new Eventsfeedback(idEvent, loggedUser.getId(), score));
                        List<Eventsfeedback> lstStars = businessLogic.getEventsFeedback(idEvent);
                        lstStars.add(new Eventsfeedback(idEvent, idUser, score));
                        
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 0)
                                            .add("message", "Evento votato correttamente.")
                                            .add("score", Useful.calculateStars(lstStars)))
                                        .build();
                    }

                    out.print(ContentGenerator.getOutputJson(jsonArray));
                    
                    break;
                case "showEvent":
                    idEvent = Integer.parseInt(request.getParameter("ide"));
                    
                    Events e = businessLogic.getEvent(idEvent);
                    if(e != null) {
                        List<Eventsfeedback> lstStars = businessLogic.getEventsFeedback(e.getId());
                            
                        htmlContent = new BlogPost()
                                        .setTitle(e.getName())
                                        .setContent(e.getDescription())
                                        .setAuthor(e.getPublisher())
                                        .setStars(Useful.calculateStars(lstStars))
                                        .setRatesNumber(lstStars.size())
                                        .setID(""+e.getId())
                                        .print();
                        //inserisci un commento sull'evento
                        Users u=(Users) session.getAttribute("loggedUser");
                        if(u!=null){
                            htmlContent +=  "<div class='evento-comment'>" +
                                            "    <div class='evento-comment-avatar'>" +
                                            "        <img src='images/no-avatar.jpg' width='80' height='80'/>" +
                                            "    </div>" +
                                            "    <div class='evento-comment-content'>" +
                                            "        <div class='evento-comment-header'>" +
                                            "            <h3>"+u.getUsername()+"</h3>" +
                                            "        </div>" +
                                            "        <div class='evento-comment-inner'>" +
                                            "            <form action='Controller?type=insertComment' method='POST'> " +
                                            "                <input type='text' name='comment'/>"+      
                                            "                <input type='hidden' name='idEvent' value='"+e.getId()+"'/>"+
                                            "                <input type='submit' value='Inserisci' class='evento-button' />" +
                                            "            </form>" +
                                            "        </div>" +
                                            "    </div>" +
                                            "</div>";
                        }
                        
                        //stampa commenti di quell'evento
                        LinkedList<Comments> comments=(LinkedList<Comments>)businessLogic.getComment(e.getId());
                        
                        for(Comments c:comments){
                            Comment tmp = new Comment();
                            tmp.setUser(businessLogic.getUser(c.getIduser()).getUsername());
                            tmp.setContent(StringHelper.convertFromUTF8(c.getComment()));
                            tmp.setDate(c.getDate());
                            htmlContent+=tmp.print();
                        }
                    }
                    else {
                        htmlContent = ContentGenerator.printError("Evento non trovato.");
                        
                        request.setAttribute("eventName", "ERRORE!");
                    }

                    request.setAttribute("content", htmlContent);
                    
                    request.getRequestDispatcher("showEvent.jsp").forward(request, response);
                    break;
                case "loadEventsLocation":
                    List<Location> listLocations = null;
                    List<Events> listEvents = null;
                    HashMap<Integer, Location> mapLocations = new HashMap<>();
                    
                    String strEventIDs = request.getParameter("eventId");
                    String strLocationIDs = "";
                    listEvents = businessLogic.getEvents(strEventIDs);

                    for(Events ev : listEvents) {
                        if(strLocationIDs.equals(""))
                            strLocationIDs += ev.getLocation();
                        else
                            strLocationIDs += "," + ev.getLocation();
                    }
                    listLocations = businessLogic.getEventLocations(strLocationIDs);
                    
                    for(Location l : listLocations) {
                        mapLocations.put(l.getId(), l);
                    }
                    
                    if(listEvents != null) {
                        jsonArrayBld = factory.createArrayBuilder();
                        for(Events evt : listEvents) {
                            Location loc = mapLocations.get(evt.getLocation());
                            jsonObj = factory.createObjectBuilder()
                                        .add("event" ,
                                                factory.createObjectBuilder()
                                                    .add("id", evt.getId())
                                                    .add("name", evt.getName())
                                                    .add("description", evt.getDescription())
                                                    .add("photo", (evt.getPhoto()!=null ? evt.getPhoto() : ""))
                                                    .add("publisher", evt.getPublisher())
                                                    .add("startdate", evt.getStartdate().toString())
                                                    .add("enddate", evt.getEnddate().toString())
                                                    .add("type", evt.getType())
                                                    .add("link", (evt.getEsternallink()!=null ? evt.getEsternallink() : ""))
                                            )
                                        .add("location" ,
                                                factory.createObjectBuilder()
                                                    .add("id", loc.getId())
                                                    .add("name", loc.getName())
                                                    .add("description", loc.getDescription())
                                                    .add("address", loc.getAddress())
                                                    .add("geolocation", loc.getGeolocation())
                                            )
                                         .build();
                            
                            jsonArrayBld.add(jsonObj);
                        }
                        
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 0)
                                            .add("locations", jsonArrayBld.build()))
                                        .build();
                    }
                    else {
                        jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 1)
                                            .add("message", ContentGenerator.printError("Nessun evento presente")))
                                        .build();
                    }
                    
                    out.print(ContentGenerator.getOutputJson(jsonArray));
                    
                    break;
                    
                default:
                    jsonArray = factory.createArrayBuilder()
                            .add(factory.createObjectBuilder()
                                    .add("status", 1)
                                    .add("message", "<li>Errore!!!! Nessun tipo specificato!!</li>"))
                            .build();

                    out.print(ContentGenerator.getOutputJson(jsonArray));

                    break;
            }
        } 
        catch (ParseException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        } 
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        session = request.getSession();
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        session = request.getSession();

        try (PrintWriter out = response.getWriter()) {
            switch (request.getParameter("type")) {
                case "login":
                    boolean remember = (request.getParameter("remember") != null && request.getParameter("remember").equals("on"));
                    String user = request.getParameter("username");
                    String pwd = request.getParameter("pwd");
                    String pwddb = DigestUtils.sha1Hex(user + ":EvenTO:" + pwd);

                    // logs in the user
                    loggedUser = businessLogic.loginUser(user, pwddb);

                    if (loggedUser != null) {
                        // writes session info
                        session.setAttribute("loggedUser", loggedUser);

                        if (remember) {
                            // defines an instance of Cookie
                            Cookie userCookie = new Cookie("EvenTO-user-info", user + "#" + pwd);
                            // sets the lifetime of the cookie in seconds (1 year)
                            userCookie.setMaxAge(31536000);
                            // writes the cookie
                            response.addCookie(userCookie);
                        }

                        // redirects to previous page
                        if(request.getParameter("redirect") != null)
                            response.sendRedirect(request.getParameter("redirect"));
                        else
                            response.sendRedirect(request.getHeader("referer"));
                    } else {
                        // redirects to error page
                        response.sendRedirect("login.jsp?error");
                    }

                    break;
                case "cookie-login":
                    String info = request.getParameter("info");
                    String[] credentials = info.split("#");
                    String pwddbC = DigestUtils.sha1Hex(credentials[0] + ":EvenTO:" + credentials[1]);

                    // logs in the user
                    Users loggedUserC = businessLogic.loginUser(credentials[0], pwddbC);

                    if (loggedUserC != null) {
                        // writes session info
                        session.setAttribute("loggedUser", loggedUserC);

                        // redirects to previous page
                        response.sendRedirect(request.getHeader("referer"));
                    } else {
                        // redirects to error page
                        response.sendRedirect("login.jsp?error");
                    }

                    break;
                default:
                    processRequest(request, response);

                    break;
            }
        } catch (ParseException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
